import oss2
import os
from datetime import datetime, timedelta


def upload_file_to_oss_and_delete_local(access_key_id, access_key_secret, endpoint, bucket_name, local_file_path,
                                        object_name=None, headers=None, delete_local=True):
    """
    上传本地文件到阿里云 OSS 并可选删除本地文件

    参数:
        access_key_id: 阿里云 AccessKey ID
        access_key_secret: 阿里云 AccessKey Secret
        endpoint: OSS 端点 (如: https://oss-cn-hangzhou.aliyuncs.com)
        bucket_name: OSS 存储桶名称
        local_file_path: 本地文件路径
        object_name: OSS 中保存的文件名 (可选，默认为本地文件名)
        delete_local: 是否删除本地文件 (默认为True)

    返回:
        文件的 URL
    """
    # 验证本地文件是否存在
    if headers is None:
        headers = {'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}
    if not os.path.exists(local_file_path):
        raise FileNotFoundError(f"本地文件不存在: {local_file_path}")

    # 如果未指定 object_name，则使用本地文件名
    if object_name is None:
        object_name = os.path.basename(local_file_path)

    try:
        # 创建认证对象
        auth = oss2.Auth(access_key_id, access_key_secret)

        # 创建 Bucket 对象
        bucket = oss2.Bucket(auth, endpoint, bucket_name)

        # 上传文件
        bucket.put_object_from_file(object_name, local_file_path,headers)

        # 生成文件的 URL
        # 如果是公共读存储桶，可以直接使用以下方式生成 URL
        url = f"https://{bucket_name}.{endpoint.replace('https://', '')}/{object_name}"

        # 如果是私有存储桶，需要生成带签名的 URL（有效期为1小时）
        # url = bucket.sign_url('GET', object_name, 3600)

        # 上传成功后删除本地文件
        if delete_local:
            os.remove(local_file_path)
            print(f"已删除本地文件: {local_file_path}")

        return url

    except oss2.exceptions.NoSuchBucket:
        raise Exception(f"存储桶不存在: {bucket_name}")
    except oss2.exceptions.AccessDenied:
        raise Exception("访问被拒绝，请检查 AccessKey 和权限")
    except Exception as e:
        raise Exception(f"上传文件到 OSS 失败: {str(e)}")


# 使用示例
if __name__ == "__main__":
    # 配置参数
    ACCESS_KEY_ID = "您的AccessKey ID"
    ACCESS_KEY_SECRET = "您的AccessKey Secret"
    ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com"  # 根据您的OSS区域修改
    BUCKET_NAME = "您的存储桶名称"
    LOCAL_FILE_PATH = "/path/to/your/local/file.jpg"  # 本地文件路径

    try:
        # 上传文件并删除本地副本
        file_url = upload_file_to_oss_and_delete_local(
            ACCESS_KEY_ID,
            ACCESS_KEY_SECRET,
            ENDPOINT,
            BUCKET_NAME,
            LOCAL_FILE_PATH,
            delete_local=True  # 设置为True以上传后删除本地文件
        )

        print(f"文件上传成功！URL: {file_url}")

    except Exception as e:
        print(f"错误: {str(e)}")